package com.kele.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author kele
 * @date 2021/10/9 16:39
 * @description lock版本的生产者消费者
 */
public class LockProduct {

    public static void main(String[] args) {
        Data2 data=new Data2();
        new Thread(()->{
            for (int i = 0; i <10 ; i++) {
                try {
                    data.add();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i <10 ; i++) {
                try {
                    data.dec();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i <10 ; i++) {
                try {
                    data.add();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();
        new Thread(()->{
            for (int i = 0; i <10 ; i++) {
                try {
                    data.dec();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"D").start();
    }


}

class Data2{

    private int data=0;
    Lock lock=new ReentrantLock();
    Condition condition = lock.newCondition();
    public  void add() throws InterruptedException {
        lock.lock();
        try {
            while (data!=0){
                condition.await();
            }
            data++;
            System.out.println(Thread.currentThread().getName()+"=>"+data);
           condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public  void dec() throws InterruptedException {
        lock.lock();
        try {
            while (data==0){
               condition.await();
            }
            data--;
            System.out.println(Thread.currentThread().getName()+"=>"+data);
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}


